class WaterMark {
    content = ''
    cavs = null

    static FONT_SIZE = 18
    static LINE_HEIGHT = 30

    constructor(content) {
        const cavs = document.createElement("canvas")
        cavs.id = "water-mark"
        cavs.width = window.innerWidth
        cavs.height = window.innerHeight
        // cavs.style.width = '100vw'
        // cavs.style.height = '100vh'
        cavs.style.position = "fixed"
        cavs.style.top = 0
        cavs.style.left = 0
        cavs.style.zIndex = 999999
        cavs.style.pointerEvents = "none"
        this.cavs = cavs
        this.content = content
        document.body.append(this.cavs)
        window.addEventListener("resize", this.resize.bind(this))
    }

    draw() {
        const ctx = this.cavs.getContext("2d")
        ctx.fillStyle = "#00000030"
        ctx.font = `${WaterMark.FONT_SIZE}px serif`
        const contentSize = ctx.measureText(this.content).width + WaterMark.FONT_SIZE
        let colNum = Math.ceil(this.cavs.width / contentSize)
        let rowNum = Math.ceil(this.cavs.height / WaterMark.LINE_HEIGHT)
        for(let y = 0; y < rowNum; ++y) {
            for(let x = 0; x < colNum; ++x) {
                let X = x * contentSize
                if(y % 2) {
                    X -= contentSize / 2
                }
                requestAnimationFrame(()=>{
                    ctx.fillText(this.content, X, y * WaterMark.LINE_HEIGHT)
                })
            }
        }
        return this
    }

    resize() {
        this.cavs.width = window.innerWidth
        this.cavs.height = window.innerHeight
        this.draw()
        return this
    }

}

/**
 * 创建水印
 * @param {string} content 水印内容
 */
function createWaterMark(content) {
    return new WaterMark(content).draw()
}

// 判断当前模块是在UMD还是ESM环境下运行  
if (typeof module !== 'undefined' && module.exports) {  
  // UMD环境下，将模块导出为CommonJS格式  
  module.exports = createWaterMark;  
} else if (typeof define === 'function' && define.amd) {  
  // UMD环境下，使用AMD规范进行导出  
  define(['dependency'], function(dependency) {  
    return createWaterMark;  
  });  
} else {  
  // ESM环境下，使用默认导出  
  export default createWaterMark;  
}